package com.openapi.server;

import com.openapi.server.codec.MsgDecoder;
import com.openapi.server.codec.MsgEncoder;
import exsun.jt808.data.base.IdentifierManage;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.timeout.IdleStateHandler;

import java.util.concurrent.TimeUnit;

public class TCPServerChannelInitializer extends ChannelInitializer<SocketChannel> {

	public TCPServerChannelInitializer() {
	}

	@Override
	protected void initChannel(SocketChannel ch) throws Exception {
		ChannelPipeline pipeline = ch.pipeline();
		pipeline.addLast("idleStateHandler", new IdleStateHandler(0, 0, 300, TimeUnit.SECONDS));
		// 1024表示单条消息的最大长度，解码器在查找分隔符的时候，达到该长度还没找到的话会抛异常
//		pipeline.addLast(new SubDelimiterBasedFrameDecoder(2048, Unpooled.copiedBuffer(new byte[] {
//				0x7e, 0x7e }), Unpooled.copiedBuffer(new byte[] { 0x7e })));
		pipeline.addLast(new SubDelimiterBasedFrameDecoder(2048,
				Unpooled.copiedBuffer(IdentifierManage.jsalt12FileIdentifier),
				Unpooled.copiedBuffer(new byte[]{IdentifierManage.jt808Identifier, IdentifierManage.jt808Identifier}),
				Unpooled.copiedBuffer(new byte[]{IdentifierManage.jt808Identifier})));
		pipeline.addLast(new MsgDecoder());
		pipeline.addLast(new MsgEncoder());
		pipeline.addLast(new TCPServerHandler());
	}

}
